3 * User interface for the difference engine.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup DifferenceEngine
23 use MediaWiki\MediaWikiServices
;
24 use MediaWiki\Shell\Shell
;
26 /** @deprecated use class constant instead */
27 define( 'MW_DIFF_VERSION', '1.11a' );
31 * @ingroup DifferenceEngine
33 class DifferenceEngine
extends ContextSource
{
35 * Constant to indicate diff cache compatibility.
36 * Bump this when changing the diff formatting in a way that
37 * fixes important bugs or such to force cached diff views to
40 const DIFF_VERSION
= MW_DIFF_VERSION
;
72 /** @var bool Have the revisions IDs been loaded */
73 private $mRevisionsIdsLoaded = false;
75 /** @var bool Have the revisions been loaded */
76 public $mRevisionsLoaded = false;
78 /** @var int How many text blobs have been loaded, 0, 1 or 2? */
79 public $mTextLoaded = 0;
81 /** @var bool Was the diff fetched from cache? */
82 public $mCacheHit = false;
85 * Set this to true to add debug info to the HTML output.
86 * Warning: this may cause RSS readers to spuriously mark articles as "new"
89 public $enableDebugComment = false;
91 /** @var bool If true, line X is not displayed when X is 1, for example
92 * to increase readability and conserve space with many small diffs.
94 protected $mReducedLineNumbers = false;
96 /** @var string Link to action=markpatrolled */
97 protected $mMarkPatrolledLink = null;
99 /** @var bool Show rev_deleted content if allowed */
100 protected $unhide = false;
102 /** @var bool Refresh the diff cache */
103 protected $mRefreshCache = false;
108 * @param IContextSource $context Context to use, anything else will be ignored
109 * @param int $old Old ID we want to show and diff with.
110 * @param string|int $new Either revision ID or 'prev' or 'next'. Default: 0.
111 * @param int $rcid Deprecated, no longer used!
112 * @param bool $refreshCache If set, refreshes the diff cache
113 * @param bool $unhide If set, allow viewing deleted revs
115 public function __construct( $context = null, $old = 0, $new = 0, $rcid = 0,
116 $refreshCache = false, $unhide = false
118 if ( $context instanceof IContextSource
) {
119 $this->setContext( $context );
122 wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'\n" );
124 $this->mOldid
= $old;
125 $this->mNewid
= $new;
126 $this->mRefreshCache
= $refreshCache;
127 $this->unhide
= $unhide;
133 public function setReducedLineNumbers( $value = true ) {
134 $this->mReducedLineNumbers
= $value;
140 public function getDiffLang() {
141 if ( $this->mDiffLang
=== null ) {
142 # Default language in which the diff text is written.
143 $this->mDiffLang
= $this->getTitle()->getPageLanguage();
146 return $this->mDiffLang
;
152 public function wasCacheHit() {
153 return $this->mCacheHit
;
159 public function getOldid() {
160 $this->loadRevisionIds();
162 return $this->mOldid
;
168 public function getNewid() {
169 $this->loadRevisionIds();
171 return $this->mNewid
;
175 * Look up a special:Undelete link to the given deleted revision id,
176 * as a workaround for being unable to load deleted diffs in currently.
178 * @param int $id Revision ID
180 * @return string|bool Link HTML or false
182 public function deletedLink( $id ) {
183 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
184 $dbr = wfGetDB( DB_REPLICA
);
185 $arQuery = Revision
::getArchiveQueryInfo();
186 $row = $dbr->selectRow(
188 array_merge( $arQuery['fields'], [ 'ar_namespace', 'ar_title' ] ),
189 [ 'ar_rev_id' => $id ],
195 $rev = Revision
::newFromArchiveRow( $row );
196 $title = Title
::makeTitleSafe( $row->ar_namespace
, $row->ar_title
);
198 return SpecialPage
::getTitleFor( 'Undelete' )->getFullURL( [
199 'target' => $title->getPrefixedText(),
200 'timestamp' => $rev->getTimestamp()
209 * Build a wikitext link toward a deleted revision, if viewable.
211 * @param int $id Revision ID
213 * @return string Wikitext fragment
215 public function deletedIdMarker( $id ) {
216 $link = $this->deletedLink( $id );
218 return "[$link $id]";
224 private function showMissingRevision() {
225 $out = $this->getOutput();
228 if ( $this->mOldRev
=== null ||
229 ( $this->mOldRev
&& $this->mOldContent
=== null )
231 $missing[] = $this->deletedIdMarker( $this->mOldid
);
233 if ( $this->mNewRev
=== null ||
234 ( $this->mNewRev
&& $this->mNewContent
=== null )
236 $missing[] = $this->deletedIdMarker( $this->mNewid
);
239 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
240 $msg = $this->msg( 'difference-missing-revision' )
241 ->params( $this->getLanguage()->listToText( $missing ) )
242 ->numParams( count( $missing ) )
244 $out->addHTML( $msg );
247 public function showDiffPage( $diffOnly = false ) {
248 # Allow frames except in certain special cases
249 $out = $this->getOutput();
250 $out->allowClickjacking();
251 $out->setRobotPolicy( 'noindex,nofollow' );
253 // Allow extensions to add any extra output here
254 Hooks
::run( 'DifferenceEngineShowDiffPage', [ $out ] );
256 if ( !$this->loadRevisionData() ) {
257 if ( Hooks
::run( 'DifferenceEngineShowDiffPageMaybeShowMissingRevision', [ $this ] ) ) {
258 $this->showMissingRevision();
263 $user = $this->getUser();
264 $permErrors = $this->mNewPage
->getUserPermissionsErrors( 'read', $user );
265 if ( $this->mOldPage
) { # mOldPage might not be set, see below.
266 $permErrors = wfMergeErrorArrays( $permErrors,
267 $this->mOldPage
->getUserPermissionsErrors( 'read', $user ) );
269 if ( count( $permErrors ) ) {
270 throw new PermissionsError( 'read', $permErrors );
276 # Carry over 'diffonly' param via navigation links
277 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
278 $query['diffonly'] = $diffOnly;
280 # Cascade unhide param in links for easy deletion browsing
281 if ( $this->unhide
) {
282 $query['unhide'] = 1;
285 # Check if one of the revisions is deleted/suppressed
286 $deleted = $suppressed = false;
287 $allowed = $this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $user );
291 # mOldRev is false if the difference engine is called with a "vague" query for
292 # a diff between a version V and its previous version V' AND the version V
293 # is the first version of that article. In that case, V' does not exist.
294 if ( $this->mOldRev
=== false ) {
295 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
298 // Allow extensions to change the $oldHeader variable
299 Hooks
::run( 'DifferenceEngineOldHeaderNoOldRev', [ &$oldHeader ] );
301 Hooks
::run( 'DiffViewHeader', [ $this, $this->mOldRev
, $this->mNewRev
] );
303 if ( $this->mNewPage
->equals( $this->mOldPage
) ) {
304 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
307 $out->setPageTitle( $this->msg( 'difference-title-multipage',
308 $this->mOldPage
->getPrefixedText(), $this->mNewPage
->getPrefixedText() ) );
309 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
313 if ( $samePage && $this->mNewPage
->quickUserCan( 'edit', $user ) ) {
314 if ( $this->mNewRev
->isCurrent() && $this->mNewPage
->userCan( 'rollback', $user ) ) {
315 $rollbackLink = Linker
::generateRollback( $this->mNewRev
, $this->getContext() );
316 if ( $rollbackLink ) {
317 $out->preventClickjacking();
318 $rollback = '   ' . $rollbackLink;
322 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) &&
323 !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
)
325 $undoLink = Html
::element( 'a', [
326 'href' => $this->mNewPage
->getLocalURL( [
328 'undoafter' => $this->mOldid
,
329 'undo' => $this->mNewid
331 'title' => Linker
::titleAttrib( 'undo' ),
333 $this->msg( 'editundo' )->text()
335 $revisionTools['mw-diff-undo'] = $undoLink;
339 # Make "previous revision link"
340 if ( $samePage && $this->mOldRev
->getPrevious() ) {
341 $prevlink = Linker
::linkKnown(
343 $this->msg( 'previousdiff' )->escaped(),
344 [ 'id' => 'differences-prevlink' ],
345 [ 'diff' => 'prev', 'oldid' => $this->mOldid
] +
$query
348 $prevlink = ' ';
351 if ( $this->mOldRev
->isMinor() ) {
352 $oldminor = ChangesList
::flag( 'minor' );
357 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
358 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
359 $oldChangeTags = ChangeTags
::formatSummaryRow( $this->mOldTags
, 'diff', $this->getContext() );
361 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
362 '<div id="mw-diff-otitle2">' .
363 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
364 '<div id="mw-diff-otitle3">' . $oldminor .
365 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
366 '<div id="mw-diff-otitle5">' . $oldChangeTags[0] . '</div>' .
367 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
369 // Allow extensions to change the $oldHeader variable
370 Hooks
::run( 'DifferenceEngineOldHeader', [ $this, &$oldHeader, $prevlink, $oldminor,
371 $diffOnly, $ldel, $this->unhide
] );
373 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
374 $deleted = true; // old revisions text is hidden
375 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
376 $suppressed = true; // also suppressed
380 # Check if this user can see the revisions
381 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $user ) ) {
386 $out->addJsConfigVars( [
387 'wgDiffOldId' => $this->mOldid
,
388 'wgDiffNewId' => $this->mNewid
,
391 # Make "next revision link"
392 # Skip next link on the top revision
393 if ( $samePage && !$this->mNewRev
->isCurrent() ) {
394 $nextlink = Linker
::linkKnown(
396 $this->msg( 'nextdiff' )->escaped(),
397 [ 'id' => 'differences-nextlink' ],
398 [ 'diff' => 'next', 'oldid' => $this->mNewid
] +
$query
401 $nextlink = ' ';
404 if ( $this->mNewRev
->isMinor() ) {
405 $newminor = ChangesList
::flag( 'minor' );
410 # Handle RevisionDelete links...
411 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
413 # Allow extensions to define their own revision tools
414 Hooks
::run( 'DiffRevisionTools',
415 [ $this->mNewRev
, &$revisionTools, $this->mOldRev
, $user ] );
416 $formattedRevisionTools = [];
417 // Put each one in parentheses (poor man's button)
418 foreach ( $revisionTools as $key => $tool ) {
419 $toolClass = is_string( $key ) ?
$key : 'mw-diff-tool';
420 $element = Html
::rawElement(
422 [ 'class' => $toolClass ],
423 $this->msg( 'parentheses' )->rawParams( $tool )->escaped()
425 $formattedRevisionTools[] = $element;
427 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) .
428 ' ' . implode( ' ', $formattedRevisionTools );
429 $newChangeTags = ChangeTags
::formatSummaryRow( $this->mNewTags
, 'diff', $this->getContext() );
431 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
432 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
434 '<div id="mw-diff-ntitle3">' . $newminor .
435 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
436 '<div id="mw-diff-ntitle5">' . $newChangeTags[0] . '</div>' .
437 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
439 // Allow extensions to change the $newHeader variable
440 Hooks
::run( 'DifferenceEngineNewHeader', [ $this, &$newHeader, $formattedRevisionTools,
441 $nextlink, $rollback, $newminor, $diffOnly, $rdel, $this->unhide
] );
443 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
444 $deleted = true; // new revisions text is hidden
445 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
446 $suppressed = true; // also suppressed
450 # If the diff cannot be shown due to a deleted revision, then output
451 # the diff header and links to unhide (if available)...
452 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
453 $this->showDiffStyle();
454 $multi = $this->getMultiNotice();
455 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
457 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
458 # Give explanation for why revision is not visible
459 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
462 # Give explanation and add a link to view the diff...
463 $query = $this->getRequest()->appendQueryValue( 'unhide', '1' );
464 $link = $this->getTitle()->getFullURL( $query );
465 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
467 "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
471 # Otherwise, output a regular diff...
473 # Add deletion notice if the user is viewing deleted content
476 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
477 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" .
478 $this->msg( $msg )->parse() .
481 $this->showDiff( $oldHeader, $newHeader, $notice );
483 $this->renderNewRevision();
489 * Build a link to mark a change as patrolled.
491 * Returns empty string if there's either no revision to patrol or the user is not allowed to.
492 * Side effect: When the patrol link is build, this method will call
493 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
495 * @return string HTML or empty string
497 public function markPatrolledLink() {
498 if ( $this->mMarkPatrolledLink
=== null ) {
499 $linkInfo = $this->getMarkPatrolledLinkInfo();
500 // If false, there is no patrol link needed/allowed
502 $this->mMarkPatrolledLink
= '';
504 $this->mMarkPatrolledLink
= ' <span class="patrollink" data-mw="interface">[' .
507 $this->msg( 'markaspatrolleddiff' )->escaped(),
510 'action' => 'markpatrolled',
511 'rcid' => $linkInfo['rcid'],
514 // Allow extensions to change the markpatrolled link
515 Hooks
::run( 'DifferenceEngineMarkPatrolledLink', [ $this,
516 &$this->mMarkPatrolledLink
, $linkInfo['rcid'] ] );
519 return $this->mMarkPatrolledLink
;
523 * Returns an array of meta data needed to build a "mark as patrolled" link and
524 * adds the mediawiki.page.patrol.ajax to the output.
526 * @return array|false An array of meta data for a patrol link (rcid only)
527 * or false if no link is needed
529 protected function getMarkPatrolledLinkInfo() {
530 global $wgUseRCPatrol, $wgEnableAPI, $wgEnableWriteAPI;
532 $user = $this->getUser();
534 // Prepare a change patrol link, if applicable
536 // Is patrolling enabled and the user allowed to?
537 $wgUseRCPatrol && $this->mNewPage
->quickUserCan( 'patrol', $user ) &&
538 // Only do this if the revision isn't more than 6 hours older
539 // than the Max RC age (6h because the RC might not be cleaned out regularly)
540 RecentChange
::isInRCLifespan( $this->mNewRev
->getTimestamp(), 21600 )
542 // Look for an unpatrolled change corresponding to this diff
543 $db = wfGetDB( DB_REPLICA
);
544 $change = RecentChange
::newFromConds(
546 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
547 'rc_this_oldid' => $this->mNewid
,
553 if ( $change && !$change->getPerformer()->equals( $user ) ) {
554 $rcid = $change->getAttribute( 'rc_id' );
556 // None found or the page has been created by the current user.
557 // If the user could patrol this it already would be patrolled
561 // Allow extensions to possibly change the rcid here
562 // For example the rcid might be set to zero due to the user
563 // being the same as the performer of the change but an extension
564 // might still want to show it under certain conditions
565 Hooks
::run( 'DifferenceEngineMarkPatrolledRCID', [ &$rcid, $this, $change, $user ] );
569 $this->getOutput()->preventClickjacking();
570 if ( $wgEnableAPI && $wgEnableWriteAPI
571 && $user->isAllowed( 'writeapi' )
573 $this->getOutput()->addModules( 'mediawiki.page.patrol.ajax' );
582 // No mark as patrolled link applicable
587 * @param Revision $rev
591 protected function revisionDeleteLink( $rev ) {
592 $link = Linker
::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
593 if ( $link !== '' ) {
594 $link = '   ' . $link . ' ';
601 * Show the new revision of the page.
603 public function renderNewRevision() {
604 $out = $this->getOutput();
605 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
606 # Add "current version as of X" title
607 $out->addHTML( "<hr class='diff-hr' id='mw-oldid' />
608 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
609 # Page content may be handled by a hooked call instead...
610 if ( Hooks
::run( 'ArticleContentOnDiff', [ $this, $out ] ) ) {
611 $this->loadNewText();
612 $out->setRevisionId( $this->mNewid
);
613 $out->setRevisionTimestamp( $this->mNewRev
->getTimestamp() );
614 $out->setArticleFlag( true );
616 if ( !Hooks
::run( 'ArticleContentViewCustom',
617 [ $this->mNewContent
, $this->mNewPage
, $out ] )
619 // Handled by extension
622 if ( $this->getTitle()->equals( $this->mNewPage
) ) {
623 // If the Title stored in the context is the same as the one
624 // of the new revision, we can use its associated WikiPage
626 $wikiPage = $this->getWikiPage();
628 // Otherwise we need to create our own WikiPage object
629 $wikiPage = WikiPage
::factory( $this->mNewPage
);
632 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev
);
634 # WikiPage::getParserOutput() should not return false, but just in case
635 if ( $parserOutput ) {
636 // Allow extensions to change parser output here
637 if ( Hooks
::run( 'DifferenceEngineRenderRevisionAddParserOutput',
638 [ $this, $out, $parserOutput, $wikiPage ] )
640 $out->addParserOutput( $parserOutput );
646 // Allow extensions to optionally not show the final patrolled link
647 if ( Hooks
::run( 'DifferenceEngineRenderRevisionShowFinalPatrolLink' ) ) {
648 # Add redundant patrol link on bottom...
649 $out->addHTML( $this->markPatrolledLink() );
653 protected function getParserOutput( WikiPage
$page, Revision
$rev ) {
654 $parserOptions = $page->makeParserOptions( $this->getContext() );
656 if ( !$rev->isCurrent() ||
!$rev->getTitle()->quickUserCan( 'edit', $this->getUser() ) ) {
657 $parserOptions->setEditSection( false );
660 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
662 return $parserOutput;
666 * Get the diff text, send it to the OutputPage object
667 * Returns false if the diff could not be generated, otherwise returns true
669 * @param string|bool $otitle Header for old text or false
670 * @param string|bool $ntitle Header for new text or false
671 * @param string $notice HTML between diff header and body
675 public function showDiff( $otitle, $ntitle, $notice = '' ) {
676 // Allow extensions to affect the output here
677 Hooks
::run( 'DifferenceEngineShowDiff', [ $this ] );
679 $diff = $this->getDiff( $otitle, $ntitle, $notice );
680 if ( $diff === false ) {
681 $this->showMissingRevision();
685 $this->showDiffStyle();
686 $this->getOutput()->addHTML( $diff );
693 * Add style sheets for diff display.
695 public function showDiffStyle() {
696 $this->getOutput()->addModuleStyles( 'mediawiki.diff.styles' );
700 * Get complete diff table, including header
702 * @param string|bool $otitle Header for old text or false
703 * @param string|bool $ntitle Header for new text or false
704 * @param string $notice HTML between diff header and body
708 public function getDiff( $otitle, $ntitle, $notice = '' ) {
709 $body = $this->getDiffBody();
710 if ( $body === false ) {
714 $multi = $this->getMultiNotice();
715 // Display a message when the diff is empty
716 if ( $body === '' ) {
717 $notice .= '<div class="mw-diff-empty">' .
718 $this->msg( 'diff-empty' )->parse() .
722 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
726 * Get the diff table body, without header
728 * @return mixed (string/false)
730 public function getDiffBody() {
731 $this->mCacheHit
= true;
732 // Check if the diff should be hidden from this user
733 if ( !$this->loadRevisionData() ) {
735 } elseif ( $this->mOldRev
&&
736 !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
739 } elseif ( $this->mNewRev
&&
740 !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
745 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
746 && $this->mOldRev
->getId() == $this->mNewRev
->getId() )
748 if ( Hooks
::run( 'DifferenceEngineShowEmptyOldContent', [ $this ] ) ) {
754 $cache = ObjectCache
::getMainWANInstance();
755 if ( $this->mOldid
&& $this->mNewid
) {
756 $key = $this->getDiffBodyCacheKey();
759 if ( !$this->mRefreshCache
) {
760 $difftext = $cache->get( $key );
762 wfIncrStats( 'diff_cache.hit' );
763 $difftext = $this->localiseLineNumbers( $difftext );
764 $difftext .= "\n<!-- diff cache key $key -->\n";
768 } // don't try to load but save the result
770 $this->mCacheHit
= false;
772 // Loadtext is permission safe, this just clears out the diff
773 if ( !$this->loadText() ) {
777 $difftext = $this->generateContentDiffBody( $this->mOldContent
, $this->mNewContent
);
779 // Avoid PHP 7.1 warning from passing $this by reference
782 // Save to cache for 7 days
783 if ( !Hooks
::run( 'AbortDiffCache', [ &$diffEngine ] ) ) {
784 wfIncrStats( 'diff_cache.uncacheable' );
785 } elseif ( $key !== false && $difftext !== false ) {
786 wfIncrStats( 'diff_cache.miss' );
787 $cache->set( $key, $difftext, 7 * 86400 );
789 wfIncrStats( 'diff_cache.uncacheable' );
791 // Replace line numbers with the text in the user's language
792 if ( $difftext !== false ) {
793 $difftext = $this->localiseLineNumbers( $difftext );
800 * Returns the cache key for diff body text or content.
804 * @throws MWException
807 protected function getDiffBodyCacheKey() {
808 if ( !$this->mOldid ||
!$this->mNewid
) {
809 throw new MWException( 'mOldid and mNewid must be set to get diff cache key.' );
812 return wfMemcKey( 'diff', 'version', self
::DIFF_VERSION
,
813 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
817 * Generate a diff, no caching.
819 * This implementation uses generateTextDiffBody() to generate a diff based on the default
820 * serialization of the given Content objects. This will fail if $old or $new are not
821 * instances of TextContent.
823 * Subclasses may override this to provide a different rendering for the diff,
824 * perhaps taking advantage of the content's native form. This is required for all content
825 * models that are not text based.
829 * @param Content $old Old content
830 * @param Content $new New content
832 * @throws MWException If old or new content is not an instance of TextContent.
833 * @return bool|string
835 public function generateContentDiffBody( Content
$old, Content
$new ) {
836 if ( !( $old instanceof TextContent
) ) {
837 throw new MWException( "Diff not implemented for " . get_class( $old ) . "; " .
838 "override generateContentDiffBody to fix this." );
841 if ( !( $new instanceof TextContent
) ) {
842 throw new MWException( "Diff not implemented for " . get_class( $new ) . "; "
843 . "override generateContentDiffBody to fix this." );
846 $otext = $old->serialize();
847 $ntext = $new->serialize();
849 return $this->generateTextDiffBody( $otext, $ntext );
853 * Generate a diff, no caching
855 * @todo move this to TextDifferenceEngine, make DifferenceEngine abstract. At some point.
857 * @param string $otext Old text, must be already segmented
858 * @param string $ntext New text, must be already segmented
860 * @return bool|string
862 public function generateTextDiffBody( $otext, $ntext ) {
863 $diff = function () use ( $otext, $ntext ) {
864 $time = microtime( true );
866 $result = $this->textDiff( $otext, $ntext );
868 $time = intval( ( microtime( true ) - $time ) * 1000 );
869 MediaWikiServices
::getInstance()->getStatsdDataFactory()->timing( 'diff_time', $time );
870 // Log requests slower than 99th percentile
871 if ( $time > 100 && $this->mOldPage
&& $this->mNewPage
) {
873 "$time ms diff: {$this->mOldid} -> {$this->mNewid} {$this->mNewPage}" );
880 * @param Status $status
883 $error = function ( $status ) {
884 throw new FatalError( $status->getWikiText() );
887 // Use PoolCounter if the diff looks like it can be expensive
888 if ( strlen( $otext ) +
strlen( $ntext ) > 20000 ) {
889 $work = new PoolCounterWorkViaCallback( 'diff',
890 md5( $otext ) . md5( $ntext ),
891 [ 'doWork' => $diff, 'error' => $error ]
893 return $work->execute();
900 * Generates diff, to be wrapped internally in a logging/instrumentation
902 * @param string $otext Old text, must be already segmented
903 * @param string $ntext New text, must be already segmented
904 * @return bool|string
907 protected function textDiff( $otext, $ntext ) {
908 global $wgExternalDiffEngine, $wgContLang;
910 $otext = str_replace( "\r\n", "\n", $otext );
911 $ntext = str_replace( "\r\n", "\n", $ntext );
913 if ( $wgExternalDiffEngine == 'wikidiff' ||
$wgExternalDiffEngine == 'wikidiff3' ) {
914 wfDeprecated( "\$wgExternalDiffEngine = '{$wgExternalDiffEngine}'", '1.27' );
915 $wgExternalDiffEngine = false;
916 } elseif ( $wgExternalDiffEngine == 'wikidiff2' ) {
917 // Same as above, but with no deprecation warnings
918 $wgExternalDiffEngine = false;
919 } elseif ( !is_string( $wgExternalDiffEngine ) && $wgExternalDiffEngine !== false ) {
920 // And prevent people from shooting themselves in the foot...
921 wfWarn( '$wgExternalDiffEngine is set to a non-string value, forcing it to false' );
922 $wgExternalDiffEngine = false;
925 // Better external diff engine, the 2 may some day be dropped
926 // This one does the escaping and segmenting itself
927 if ( function_exists( 'wikidiff2_do_diff' ) && $wgExternalDiffEngine === false ) {
928 $wikidiff2Version = phpversion( 'wikidiff2' );
930 $wikidiff2Version !== false &&
931 version_compare( $wikidiff2Version, '1.5.0', '>=' )
933 $text = wikidiff2_do_diff(
937 $this->getConfig()->get( 'WikiDiff2MovedParagraphDetectionCutoff' )
940 // Don't pass the 4th parameter for compatibility with older versions of wikidiff2
941 $text = wikidiff2_do_diff(
947 // Log a warning in case the configuration value is set to not silently ignore it
948 if ( $this->getConfig()->get( 'WikiDiff2MovedParagraphDetectionCutoff' ) > 0 ) {
949 wfLogWarning( '$wgWikiDiff2MovedParagraphDetectionCutoff is set but has no
950 effect since the used version of WikiDiff2 does not support it.' );
954 $text .= $this->debug( 'wikidiff2' );
957 } elseif ( $wgExternalDiffEngine !== false && is_executable( $wgExternalDiffEngine ) ) {
959 $tmpDir = wfTempDir();
960 $tempName1 = tempnam( $tmpDir, 'diff_' );
961 $tempName2 = tempnam( $tmpDir, 'diff_' );
963 $tempFile1 = fopen( $tempName1, "w" );
967 $tempFile2 = fopen( $tempName2, "w" );
971 fwrite( $tempFile1, $otext );
972 fwrite( $tempFile2, $ntext );
973 fclose( $tempFile1 );
974 fclose( $tempFile2 );
975 $cmd = [ $wgExternalDiffEngine, $tempName1, $tempName2 ];
976 $result = Shell
::command( $cmd )
978 $exitCode = $result->getExitCode();
979 if ( $exitCode !== 0 ) {
980 throw new Exception( "External diff command returned code {$exitCode}. Stderr: "
981 . wfEscapeWikiText( $result->getStderr() )
984 $difftext = $result->getStdout();
985 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
986 unlink( $tempName1 );
987 unlink( $tempName2 );
993 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
994 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
995 $diffs = new Diff( $ota, $nta );
996 $formatter = new TableDiffFormatter();
997 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) );
998 $difftext .= $this->debug( 'native PHP' );
1004 * Generate a debug comment indicating diff generating time,
1005 * server node, and generator backend.
1007 * @param string $generator : What diff engine was used
1011 protected function debug( $generator = "internal" ) {
1012 global $wgShowHostnames;
1013 if ( !$this->enableDebugComment
) {
1016 $data = [ $generator ];
1017 if ( $wgShowHostnames ) {
1018 $data[] = wfHostname();
1020 $data[] = wfTimestamp( TS_DB
);
1022 return "<!-- diff generator: " .
1023 implode( " ", array_map( "htmlspecialchars", $data ) ) .
1028 * Replace line numbers with the text in the user's language
1030 * @param string $text
1034 public function localiseLineNumbers( $text ) {
1035 return preg_replace_callback(
1036 '/<!--LINE (\d+)-->/',
1037 [ $this, 'localiseLineNumbersCb' ],
1042 public function localiseLineNumbersCb( $matches ) {
1043 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) {
1047 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
1051 * If there are revisions between the ones being compared, return a note saying so.
1055 public function getMultiNotice() {
1056 if ( !is_object( $this->mOldRev
) ||
!is_object( $this->mNewRev
) ) {
1058 } elseif ( !$this->mOldPage
->equals( $this->mNewPage
) ) {
1059 // Comparing two different pages? Count would be meaningless.
1063 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
1064 $oldRev = $this->mNewRev
; // flip
1065 $newRev = $this->mOldRev
; // flip
1066 } else { // normal case
1067 $oldRev = $this->mOldRev
;
1068 $newRev = $this->mNewRev
;
1071 // Sanity: don't show the notice if too many rows must be scanned
1072 // @todo show some special message for that case
1073 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev, 1000 );
1074 if ( $nEdits > 0 && $nEdits <= 1000 ) {
1075 $limit = 100; // use diff-multi-manyusers if too many users
1076 $users = $this->mNewPage
->getAuthorsBetween( $oldRev, $newRev, $limit );
1077 $numUsers = count( $users );
1079 if ( $numUsers == 1 && $users[0] == $newRev->getUserText( Revision
::RAW
) ) {
1080 $numUsers = 0; // special case to say "by the same user" instead of "by one other user"
1083 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
1086 return ''; // nothing
1090 * Get a notice about how many intermediate edits and users there are
1092 * @param int $numEdits
1093 * @param int $numUsers
1098 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
1099 if ( $numUsers === 0 ) {
1100 $msg = 'diff-multi-sameuser';
1101 } elseif ( $numUsers > $limit ) {
1102 $msg = 'diff-multi-manyusers';
1105 $msg = 'diff-multi-otherusers';
1108 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
1112 * Get a header for a specified revision.
1114 * @param Revision $rev
1115 * @param string $complete 'complete' to get the header wrapped depending
1116 * the visibility of the revision and a link to edit the page.
1118 * @return string HTML fragment
1120 public function getRevisionHeader( Revision
$rev, $complete = '' ) {
1121 $lang = $this->getLanguage();
1122 $user = $this->getUser();
1123 $revtimestamp = $rev->getTimestamp();
1124 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
1125 $dateofrev = $lang->userDate( $revtimestamp, $user );
1126 $timeofrev = $lang->userTime( $revtimestamp, $user );
1128 $header = $this->msg(
1129 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
1135 if ( $complete !== 'complete' ) {
1139 $title = $rev->getTitle();
1141 $header = Linker
::linkKnown( $title, $header, [],
1142 [ 'oldid' => $rev->getId() ] );
1144 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
1145 $editQuery = [ 'action' => 'edit' ];
1146 if ( !$rev->isCurrent() ) {
1147 $editQuery['oldid'] = $rev->getId();
1150 $key = $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold';
1151 $msg = $this->msg( $key )->escaped();
1152 $editLink = $this->msg( 'parentheses' )->rawParams(
1153 Linker
::linkKnown( $title, $msg, [], $editQuery ) )->escaped();
1154 $header .= ' ' . Html
::rawElement(
1156 [ 'class' => 'mw-diff-edit' ],
1159 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
1160 $header = Html
::rawElement(
1162 [ 'class' => 'history-deleted' ],
1167 $header = Html
::rawElement( 'span', [ 'class' => 'history-deleted' ], $header );
1174 * Add the header to a diff body
1176 * @param string $diff Diff body
1177 * @param string $otitle Old revision header
1178 * @param string $ntitle New revision header
1179 * @param string $multi Notice telling user that there are intermediate
1180 * revisions between the ones being compared
1181 * @param string $notice Other notices, e.g. that user is viewing deleted content
1185 public function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
1186 // shared.css sets diff in interface language/dir, but the actual content
1187 // is often in a different language, mostly the page content language/dir
1188 $header = Html
::openElement( 'table', [
1189 'class' => [ 'diff', 'diff-contentalign-' . $this->getDiffLang()->alignStart() ],
1190 'data-mw' => 'interface',
1192 $userLang = htmlspecialchars( $this->getLanguage()->getHtmlCode() );
1194 if ( !$diff && !$otitle ) {
1196 <tr style=\"vertical-align: top;\" lang=\"{$userLang}\">
1197 <td class=\"diff-ntitle\">{$ntitle}</td>
1201 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1203 <col class=\"diff-marker\" />
1204 <col class=\"diff-content\" />
1205 <col class=\"diff-marker\" />
1206 <col class=\"diff-content\" />";
1213 if ( $otitle ||
$ntitle ) {
1215 <tr style=\"vertical-align: top;\" lang=\"{$userLang}\">
1216 <td colspan=\"$colspan\" class=\"diff-otitle\">{$otitle}</td>
1217 <td colspan=\"$colspan\" class=\"diff-ntitle\">{$ntitle}</td>
1222 if ( $multi != '' ) {
1223 $header .= "<tr><td colspan=\"{$multiColspan}\" style=\"text-align: center;\" " .
1224 "class=\"diff-multi\" lang=\"{$userLang}\">{$multi}</td></tr>";
1226 if ( $notice != '' ) {
1227 $header .= "<tr><td colspan=\"{$multiColspan}\" style=\"text-align: center;\" " .
1228 "lang=\"{$userLang}\">{$notice}</td></tr>";
1231 return $header . $diff . "</table>";
1235 * Use specified text instead of loading from the database
1236 * @param Content $oldContent
1237 * @param Content $newContent
1240 public function setContent( Content
$oldContent, Content
$newContent ) {
1241 $this->mOldContent
= $oldContent;
1242 $this->mNewContent
= $newContent;
1244 $this->mTextLoaded
= 2;
1245 $this->mRevisionsLoaded
= true;
1249 * Set the language in which the diff text is written
1250 * (Defaults to page content language).
1251 * @param Language|string $lang
1254 public function setTextLanguage( $lang ) {
1255 $this->mDiffLang
= wfGetLangObj( $lang );
1259 * Maps a revision pair definition as accepted by DifferenceEngine constructor
1260 * to a pair of actual integers representing revision ids.
1262 * @param int $old Revision id, e.g. from URL parameter 'oldid'
1263 * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
1265 * @return int[] List of two revision ids, older first, later second.
1266 * Zero signifies invalid argument passed.
1267 * false signifies that there is no previous/next revision ($old is the oldest/newest one).
1269 public function mapDiffPrevNext( $old, $new ) {
1270 if ( $new === 'prev' ) {
1271 // Show diff between revision $old and the previous one. Get previous one from DB.
1272 $newid = intval( $old );
1273 $oldid = $this->getTitle()->getPreviousRevisionID( $newid );
1274 } elseif ( $new === 'next' ) {
1275 // Show diff between revision $old and the next one. Get next one from DB.
1276 $oldid = intval( $old );
1277 $newid = $this->getTitle()->getNextRevisionID( $oldid );
1279 $oldid = intval( $old );
1280 $newid = intval( $new );
1283 return [ $oldid, $newid ];
1289 private function loadRevisionIds() {
1290 if ( $this->mRevisionsIdsLoaded
) {
1294 $this->mRevisionsIdsLoaded
= true;
1296 $old = $this->mOldid
;
1297 $new = $this->mNewid
;
1299 list( $this->mOldid
, $this->mNewid
) = self
::mapDiffPrevNext( $old, $new );
1300 if ( $new === 'next' && $this->mNewid
=== false ) {
1301 # if no result, NewId points to the newest old revision. The only newer
1302 # revision is cur, which is "0".
1307 'NewDifferenceEngine',
1308 [ $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new ]
1313 * Load revision metadata for the specified articles. If newid is 0, then compare
1314 * the old article in oldid to the current article; if oldid is 0, then
1315 * compare the current article to the immediately previous one (ignoring the
1318 * If oldid is false, leave the corresponding revision object set
1319 * to false. This is impossible via ordinary user input, and is provided for
1324 public function loadRevisionData() {
1325 if ( $this->mRevisionsLoaded
) {
1329 // Whether it succeeds or fails, we don't want to try again
1330 $this->mRevisionsLoaded
= true;
1332 $this->loadRevisionIds();
1334 // Load the new revision object
1335 if ( $this->mNewid
) {
1336 $this->mNewRev
= Revision
::newFromId( $this->mNewid
);
1338 $this->mNewRev
= Revision
::newFromTitle(
1341 Revision
::READ_NORMAL
1345 if ( !$this->mNewRev
instanceof Revision
) {
1349 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1350 $this->mNewid
= $this->mNewRev
->getId();
1351 $this->mNewPage
= $this->mNewRev
->getTitle();
1353 // Load the old revision object
1354 $this->mOldRev
= false;
1355 if ( $this->mOldid
) {
1356 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1357 } elseif ( $this->mOldid
=== 0 ) {
1358 $rev = $this->mNewRev
->getPrevious();
1360 $this->mOldid
= $rev->getId();
1361 $this->mOldRev
= $rev;
1363 // No previous revision; mark to show as first-version only.
1364 $this->mOldid
= false;
1365 $this->mOldRev
= false;
1367 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1369 if ( is_null( $this->mOldRev
) ) {
1373 if ( $this->mOldRev
) {
1374 $this->mOldPage
= $this->mOldRev
->getTitle();
1377 // Load tags information for both revisions
1378 $dbr = wfGetDB( DB_REPLICA
);
1379 if ( $this->mOldid
!== false ) {
1380 $this->mOldTags
= $dbr->selectField(
1383 [ 'ts_rev_id' => $this->mOldid
],
1387 $this->mOldTags
= false;
1389 $this->mNewTags
= $dbr->selectField(
1392 [ 'ts_rev_id' => $this->mNewid
],
1400 * Load the text of the revisions, as well as revision data.
1404 public function loadText() {
1405 if ( $this->mTextLoaded
== 2 ) {
1409 // Whether it succeeds or fails, we don't want to try again
1410 $this->mTextLoaded
= 2;
1412 if ( !$this->loadRevisionData() ) {
1416 if ( $this->mOldRev
) {
1417 $this->mOldContent
= $this->mOldRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1418 if ( $this->mOldContent
=== null ) {
1423 if ( $this->mNewRev
) {
1424 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1425 Hooks
::run( 'DifferenceEngineLoadTextAfterNewContentIsLoaded', [ $this ] );
1426 if ( $this->mNewContent
=== null ) {
1435 * Load the text of the new revision, not the old one
1439 public function loadNewText() {
1440 if ( $this->mTextLoaded
>= 1 ) {
1444 $this->mTextLoaded
= 1;
1446 if ( !$this->loadRevisionData() ) {
1450 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1452 Hooks
::run( 'DifferenceEngineAfterLoadNewText', [ $this ] );